import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:tin_flutter/app/network/error_response_handler.dart';
import 'package:tin_flutter/app/network/retrofit_client.dart';
import 'package:tin_flutter/app/tools/loading_dialog.dart';
import 'package:tin_flutter/app/tools/logger.dart';
import 'package:tin_flutter/ui/bean/base_response_entity.dart';
import 'package:tin_flutter/ui/bean/response/home_content_entity.dart';
import 'package:tin_flutter/ui/bean/response/recommend_product_entity.dart';

import '../../ui/bean/response/brand_product_entity.dart';
import '../../ui/bean/response/login_response_entity.dart';

class HttpService {
  static late RetrofitClient _client;

  static void doInit() {
    var dio = Dio();
    dio.interceptors.add(InterceptorsWrapper(onRequest: (options, handler) {
      options.headers["Content-Type"] = "application/x-www-form-urlencoded";
      // options.headers["Accept-Language"] = Intr().currentLocale().languageCode;

      //设备信息【PC:PC网页端,MP:移动端,APP:原生APP】
      //网站ID
      //机器型号
      //系统版本号【APP强制使用】
      // var commonParams = {"machineModel":Constants.model(),"siteId":"9000","siteType":"1","terminal":"APP","version":Constants.version()};
      // options.queryParameters.addAll(commonParams);
      loggerArray([
        "发起请求",
        "${options.baseUrl}${options.path}\n",
        "${options.method}\n",
        "${options.headers}\n",
        options.data ?? options.queryParameters
      ]);
      handler.next(options);
    }, onResponse: (response, handler) {
      loggerArray([
        "返回响应",
        response.requestOptions.path,
        response.statusCode,
        "${response.statusMessage}\n",
        jsonEncode(response.data)
      ]);
      if (response.statusCode == 200) {
        handler.next(response);
      } else {
        ErrorResponseHandler()
            .onErrorHandle({"code": response.statusCode, "message": response.statusMessage});
      }
    }, onError: (DioException e, handler) {
      loggerArray(["异常响应", e.toString()]);
      handler.next(e);
    }));
    _client = RetrofitClient(dio);
  }

  ///游戏返回体
  ///封装请求体，自动处理各种异常问题
  static Future<T> buildFuture<T>(RequestCallback callback,
      {bool loading = true, bool needMsg = false, bool errorHandler = true}) async {
    if (loading) {
      LoadingDialog.show(text: "登录中...");
    }
    try {
      var value = await callback.call();
      if (loading) {
        LoadingDialog.dismiss();
      }
      if (value.isOk()) {
        ///data为null时处理
        return Future.value(value.data ?? (needMsg ? value.errorMsg.toString() : ""));
      } else {
        if (errorHandler) {
          ErrorResponseHandler()
              .onErrorHandle({"code": value.errorCode, "message": value.errorMsg.toString()});
        }
        return Future.error(value.errorMsg.toString());
      }
    } catch (error) {
      loggerArray(["请求异常信息", error]);
      if (loading) {
        LoadingDialog.dismiss();
      }
      if (errorHandler) {
        ErrorResponseHandler().onErrorHandle(error);
      }
      return Future.error(error);
    }
  }

  /// 登录
  /// * [encryptedData] 加密数据
  static Future<LoginResponseEntity> login(String encryptedData) {
    return buildFuture<LoginResponseEntity>(() => _client.login(encryptedData), loading: true);
  }

  /// 获取首页内容
  static Future<HomeContentEntity> getHomeContent() {
    return buildFuture<HomeContentEntity>(() => _client.getHomeContent(), loading: true);
  }

  /// 分页获取推荐列表
  /// * [page] 页码
  /// * [size] 每页数量
  static Future<List<RecommendProductEntity>> getRecommendProductList(int page, int size) {
    return buildFuture<List<RecommendProductEntity>>(
        () => _client.getRecommendProductList(page, size),
        loading: false);
  }

  /// 分页获取品牌推荐列表
  /// * [page] 页码
  /// * [size] 每页数量
  static Future<List<HomeContentBrandList>> getRecommendBrandList(int page, int size) {
    return buildFuture<List<HomeContentBrandList>>(() => _client.getRecommendBrandList(page, size),
        loading: false);
  }

  /// 获取品牌详情
  /// * [brand] 品牌id
  static Future<HomeContentBrandList> getBrandDetail(int brand) {
    return buildFuture<HomeContentBrandList>(() => _client.getBrandDetail(brand), loading: false);
  }

  /// 分页获取品牌商品列表
  /// * [page] 页码
  /// * [size] 每页数量
  static Future<BrandProductEntity> getBrandProductList(int brandId, int page, int size) {
    return buildFuture<BrandProductEntity>(
        () => _client.getBrandProductList(brandId, page, size),
        loading: false);
  }
}

typedef RequestCallback = Future<BaseResponseEntity<dynamic>> Function();
